import { Emitter } from '@/ts/base/common';
import { IForm } from '@/ts/core';
import { Form } from 'devextreme-react';
import { GroupItem, SimpleItem } from 'devextreme-react/form';
import React, { useEffect, useState } from 'react';
import CustomBuilder from './formRule/builder';
import { FieldInfo } from 'typings/globelType';
import useAsyncLoad from '@/hooks/useAsyncLoad';
import Classify from './formRule/builder/classify';
import { tryParseJson } from '@/utils/tools';
import { FullEntityColumns } from '@/config/column';
import { FieldModel, FiledLookup, ClassifyTreeType } from '@/ts/base/model';

interface IAttributeProps {
  current: IForm;
  notifyEmitter: Emitter;
}

const FormConfig: React.FC<IAttributeProps> = ({ notifyEmitter, current }) => {
  const [fields, setFields] = useState<FieldInfo[]>([]);
  const [speciesFields, setSpeciesFields] = useState<FieldModel[]>([]);
  const [loaded] = useAsyncLoad(async () => {
    const resultFields = FullEntityColumns(await current.loadFields());
    const valueFields: FieldInfo[] = [];
    for (const item of resultFields) {
      var field = {
        id: item.id,
        name: item.code,
        dataField: item.code,
        caption: item.name,
      };
      switch (item.valueType) {
        case '数值型':
          valueFields.push({ ...field, dataType: 'number', fieldType: '数值型' });
          break;
        case '日期型':
          valueFields.push({ ...field, dataType: 'date', fieldType: '日期型' });
          break;
        case '时间型':
          valueFields.push({ ...field, dataType: 'datetime', fieldType: '时间型' });
          break;
        case '选择型':
          valueFields.push({
            ...field,
            dataType: 'string',
            fieldType: '选择型',
            lookup: {
              displayExpr: 'text',
              valueExpr: 'value',
              allowClearing: true,
              dataSource: item.lookups,
            },
          });
          break;
        case '描述型':
          valueFields.push({ ...field, dataType: 'string', fieldType: '描述型' });
          break;
      }
    }
    setFields(valueFields);
    setSpeciesFields(resultFields.filter((i) => i.valueType === '分类型'));
  }, [current]);

  const emptyData: any = { type: 'condition', relation: '_all_', value: [], _tempId: '1', parentId: null };
  const [conditionText, setConditionText] = useState('[]');
  const [classifyDisplay, setClassifyDisplay] = useState(emptyData);

  const notityAttrChanged = () => {
    notifyEmitter.changCallback('form');
  };

  const setFilterCondition = (value: string, text: string) => {
    if (!current.metadata.options?.dataRange) {
      current.metadata.options!.dataRange = {};
    }
    if (tryParseJson(value)) {
      current.metadata.options!.dataRange!.filterExp = value;
      current.metadata.options!.dataRange!.filterDisplay = text;
    } else {
      current.metadata.options!.dataRange!.filterExp = undefined;
      current.metadata.options!.dataRange!.filterDisplay = undefined;
    }
  };

  const onClassifyChange = (result: any) => {
    if (!current.metadata.options?.dataRange) {
      current.metadata.options!.dataRange = {};
    }
    if (Object.keys(result?.value)?.length > 0) {
      current.metadata.options!.dataRange!.classifyExp = JSON.stringify(result.value);
      current.metadata.options!.dataRange!.classifyDisplay = JSON.stringify(result.data);
    } else {
      current.metadata.options!.dataRange!.classifyExp = undefined;
      current.metadata.options!.dataRange!.classifyDisplay = undefined;
    }
  };

  useEffect(() => {
    if (!current.metadata.options) {
      current.metadata.options = { itemWidth: 300 };
    }
    const filterDisplay = tryParseJson(current.metadata.options.dataRange?.filterDisplay);
    if (filterDisplay) {
      setConditionText(JSON.stringify(filterDisplay));
    }
    const classifyDisplay = tryParseJson(
      current.metadata.options.dataRange?.classifyDisplay,
    );
    if (classifyDisplay) {
      setClassifyDisplay(classifyDisplay);
    }
  }, [current]);
  return (
    <>
      <Form
        scrollingEnabled
        height={'calc(100vh - 130px)'}
        formData={current.metadata}
        onFieldDataChanged={notityAttrChanged}>
        <GroupItem>
          <SimpleItem dataField="name" isRequired={true} label={{ text: '名称' }} />
          <SimpleItem dataField="code" isRequired={true} label={{ text: '代码' }} />
          <SimpleItem
            dataField="options.itemWidth"
            editorType="dxNumberBox"
            label={{ text: '特性宽度' }}
            editorOptions={{
              min: 200,
              max: 800,
              step: 10,
              format: '#(px)',
              defaultValue: 300,
              showClearButton: true,
              showSpinButtons: true,
            }}
          />
          <SimpleItem
            dataField="remark"
            editorType="dxTextArea"
            isRequired={true}
            label={{ text: '表单描述' }}
            editorOptions={{
              height: 100,
            }}
          />
        </GroupItem>
        <GroupItem caption="查看设置">
          <SimpleItem
            label={{ text: '值筛选' }}
            render={() =>
              loaded && (
                <CustomBuilder
                  fields={fields}
                  displayText={conditionText}
                  onValueChanged={(value, text) => {
                    setConditionText(text);
                    setFilterCondition(value, text);
                  }}
                />
              )
            }
          />
          <SimpleItem
            label={{ text: '类筛选' }}
            render={() =>
              loaded && (
                <Classify
                  speciesFields={speciesFields}
                  classifyTreeData={classifyDisplay}
                  onChange={onClassifyChange}
                />
              )
            }
          />
        </GroupItem>
      </Form>
    </>
  );
};

export default FormConfig;
